import io.vertx.core.AbstractVerticle
import io.vertx.core.Vertx
import io.vertx.core.parsetools.RecordParser

import java.util.stream.Stream

/**
 * Created by Lzx on 2017/12/7.
 */
class Client extends AbstractVerticle {

    static void main(def args) {
        Vertx.vertx().deployVerticle(Client.newInstance())
    }

    @Override
    void start() throws Exception {
        vertx.createNetClient().connect(1234, "localhost", { res ->

            if (res.succeeded()) {
                def socket = res.result()

                RecordParser.newDelimited("\n", socket)
                        .endHandler({v -> socket.close()})
                        .exceptionHandler({ t->
                    t.printStackTrace()
                    socket.close()
                })
                        .handler({ buffer ->
                    String greeting = buffer.toString("UTF-8")
                    System.out.println("Net client receiving: " + greeting)
                })

                // Now send some data
                Stream.of("John", "Joe", "Lisa", "Bill").forEach({name ->
                    System.out.println("Net client sending: " + name)
                    socket.write(name).write("\n")
                })

            } else {
                System.out.println("Failed to connect " + res.cause())
            }
        })
    }
}
